package com.aistar.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5 {

    /**
     * 给指定字符串按照md5算法加密
     * @param psd  需要加密的密码
     */
    public static String encoder(String psd) {
        StringBuffer stringBuffer = new StringBuffer();
        //1.指定加密算法类型
        try {
           // psd = psd+"vxcfgbdsdf";
            MessageDigest digest = MessageDigest.getInstance("Md5");
            //2.将需要加密的字符串转换为byte类型的数组然后进行随机的hash过程(打乱字符串)
            byte[] bs = digest.digest(psd.getBytes());   //数组的长度为16
            System.out.println(bs);
            //3.循环遍历bs，然后让其生成32位字符串，固定写法

            //5.打印测试

            for(byte b:bs){  //每个byte  b是8位  0xff 8位
                int i = b & 0xff;
                //int型的i 转换位16进制的字符
                String hexString = Integer.toHexString(i);
                //补充
                if(hexString.length()<2){
                    hexString = "0" + hexString;
                }
                //4.拼接
                stringBuffer.append(hexString);
            }

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }
}
